//
//  Copyright (C) 2012 Vadim Ushakov
// 
//  This program is free software; you can redistribute it and/or modify it
//  under the terms of the GNU General Public License as published by the Free
//  Software Foundation; either version 2 of the License, or (at your option)
//  any later version.
// 
//  This program is distributed in the hope that it will be useful, but
//  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
//  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
//  for more details.
//  
//  You should have received a copy of the GNU General Public License along
//  with this program; if not, write to the Free Software Foundation, Inc.,
//  59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//


#include "kernelError.h"
#include "kernelSpinLock.h"
#include "kernelPerformanceCounter.h"
#include "kernelMallocStatic.h"
#include <string.h>

#define STATIC_POOL_SIZE (1024 * 64)

static char pool[STATIC_POOL_SIZE];
static int pool_position = 0;

static int freePerfCounter = -1;
static int usedPerfCounter = -1;
static int allocationsPerfCounter = -1;

static SPIN_LOCK_DECL(poolLock, kernelProcessorLevelDispatch);


void * kernelMallocStatic(unsigned size)
{
	int oldLevel = kernelSpinLockAcquire(&poolLock);
	if (oldLevel < 0)
	{
		kernelError("Failed to allocate %d bytes from static pool (no lock)", size);
		return 0;
	}

    int new_position = pool_position + size;
    if (new_position >= STATIC_POOL_SIZE || new_position < pool_position)
	{
		kernelError("Failed to allocate %d bytes from static pool (only %d bytes available)", size, STATIC_POOL_SIZE - pool_position);
		return 0;
	}

	void * result = pool + pool_position;
	pool_position = new_position;

	kernelSpinLockRelease(&poolLock, oldLevel);

	if (freePerfCounter >= 0)
		kernelPerformanceCounterSetI(freePerfCounter, STATIC_POOL_SIZE - pool_position);
	if (usedPerfCounter >= 0)
		kernelPerformanceCounterSetI(usedPerfCounter, pool_position);
	if (allocationsPerfCounter >= 0)
		kernelPerformanceCounterInc1(allocationsPerfCounter);

	return (result);
}

void kernelMallocStaticInitialize1(void)
{
}

void kernelMallocStaticInitialize2(void)
{
	freePerfCounter = kernelPerformanceCounterRegisterStatic("static_pool.bytes_free");
	usedPerfCounter = kernelPerformanceCounterRegisterStatic("static_pool.bytes_used");
	allocationsPerfCounter = kernelPerformanceCounterRegisterStatic("static_pool.allocations");
}
